/*
 * @Author: GKN
 * @Date: 2023-11-28 10:25:27
 * @LastEditTime: 2024-02-02 11:15:26
 * @LastEditors: GKN
 * @Description: 
 * @FilePath: \mod\src\utils\utils.js
 * 可以输入预定的版权声明、个性签名、空行等
 */
import { ElMessage,ElNotification,ElMessageBox } from 'element-plus'
import CryptoJS from 'crypto-js';
import router from '@/router'
import httpApi from '@/api/http'
import api from '@/api/api'
import rgbaster from 'rgbaster';
import { useStore } from 'vuex';
// const store = new useStore();
import store from '../store/index.js'
function rgbToHex(red, green, blue) {
    const toHex = (color) => {
      let hex = color.toString(16);
      return hex.length == 1 ? "0" + hex : hex;
    };
   
    return "#" + toHex(red) + toHex(green) + toHex(blue);
  }
export default {
    // 提醒/通知
    msg(type,str,t=2){
        if(t == 1){
            ElNotification({
                title: '',
                message: str,
                type: type,
            })
        }
        if(t == 2){
            ElMessage[type](str)
        }
        if(t == 3){
            ElMessageBox.alert(str, '提示', {
                confirmButtonText: '好的',
                callback: (action) => {
                    router.go(-1)
                },
            })
        }
    },
    timestampToDateTime(timestamp) {
        // 将时间戳转换为Date对象
        const date = new Date(timestamp * 1000);
      
        // 获取年、月、日、时、分、秒
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，所以加1
        const day = date.getDate().toString().padStart(2, '0');
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        const seconds = date.getSeconds().toString().padStart(2, '0');
      
        // 格式化日期字符串
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      },
    // 年月日 -周几
    today(){
        var today = new Date();
        var year = today.getFullYear();
        var month = today.getMonth() + 1;
        var day = today.getDate();
        var weekday = today.getDay();
        let arr=['日','一','二','三','四','五','六']
        return year + "年" + month + "月" + day + "日 星期" + arr[weekday]
    },
    // 时间戳转换
    timeChange(timestamp) {
        let date = new Date(timestamp);
        let formattedDate = date.toLocaleString();
        return formattedDate;
    },
    // 数组按num 个一组重组
    carveUp (arr,num){
        let newCardList = [];
        for (var i = 0; i < arr.length; i += num) {
            newCardList.push(arr.slice(i, i + num));
        }
        return newCardList;
    },
    // 截取url /后
    jqurl (url){
        var parts = url.split("/");
        return parts[parts.length - 1];
    },
    // 查询数组内符合的元素
    extract(sourceArray, indexArray , indexKey){
        var array = [];
        for (var i = 0; i < sourceArray.length; i++) {
            if (indexArray.indexOf(sourceArray[i][indexKey]) > -1) {
                if(sourceArray[i]!==undefined){
                    array.push(sourceArray[i]);
                }
            }
        }
        return array;
    },
    // 数据加密
    encry (arr){
        const ob = CryptoJS.AES.encrypt(JSON.stringify(arr),'query').toString();
        return ob;
    },
    // 数据解密
    decrypt (value,name){
        const ob = JSON.parse(CryptoJS.AES.decrypt(value,name?name:'query').toString(CryptoJS.enc.Utf8))
        return ob;
    },
    getAd(id,ty,callback){
        httpApi.request(api.list_advert+'?nid='+id,'get',{},false, function (res) {
            if(res&&res.data){
              callback(res.data.data) ;
            }else{
                callback({list:[]}) ;
            }
          })
    },
    downloadUrl(url,fileName,id){
        window.location.href = url
        httpApi.request(api.list_down,'post',{
            "fileName": fileName,
            "newsId": id
        },false, function (res) {
            
          })
    },
    openUrl(item){
        if(!item){
            return;
        }
        if(/https?:\/\//i.test(item.url)||/http?:\/\//i.test(item.url)){
            if(item.ty == 1){
                window.open(item.url)
            }
            if(item.ty == 2){
                window.location.href = item.url
            }
        }else{
            if(item.nid){
                if(item.ty == 1){
                }
                if(item.ty == 2){
                    
                }
            }
        }
        
    },
    openInfo(first_title,name,item,path){
        const arr = {
            title:name,
            id:item.newsId,
            path:path,
            first_title:first_title,
            first_path:-1
        }
        const ob = CryptoJS.AES.encrypt(JSON.stringify(arr),'query').toString()
        const routeUrl = router.resolve({
            path:'/animatedly/info',
            query:{
                ob:ob
            }
        });
        window.open(routeUrl.href, "_blank");
    },
    openMoreList(first_title,name,id){
        const arr = {
            title:name,
            id:id,
            first_title:first_title,
        }
        const ob = CryptoJS.AES.encrypt(JSON.stringify(arr),'query').toString()
        router.push({
            path:'/animatedly/list',
            query:{
              ob:ob
            }
        });
    },
    // 截取字符串内参数
    queryParam(str,name){
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = str.match(reg);
        if (r != null) {
        return r[2];
        }
        return null;
    },
    // 获取用户信息
    getUserInfo(callback){
        const loginData = JSON.parse(localStorage.getItem( 'loginData' ))
        httpApi.request(api.userInfo+loginData.xUserid,'get',{},false, function (res) {
            if(res&&res.data){
                store.commit('changeName', res.data.data.name)
                store.commit('changeVip', res.data.data.vip)
                store.commit('changeUser', res.data.data)
                localStorage.setItem( 'user', JSON.stringify(res.data.data));
                callback(res.data.data) ;
              
            }else{
                callback(null) ;
            }
          })
    },
    // 获取id对应得列表数据（分页）
    getNewList(num,id,page,tag,callback){
        httpApi.request(api.list_news+'?nextTag='+page.nextTag+'&nid='+id+'&pageSize='+num+'&prevTag='+page.prevTag+'&tag='+tag,'get',{},false, function (res) {
            if(res&&res.data){
                if(Object.keys(res.data).length!==0){
                    callback(res.data.data)
                }else{
                    callback([]) ;
                }
              
            }else{
                callback([]);
            }
        })
    },
    // 获取企业成果库-企业下文章
    getEnterpriseNews(eid,id,callback){
        httpApi.request(api.enterpriseNews+eid+'?&nid='+id,'get',{},false, function (res) {
            if(res&&res.data){
                if(Object.keys(res.data).length!==0){
                    callback(res.data.data)
                }else{
                    callback([]) ;
                }
              
            }else{
                callback([]);
            }
        })
    },
    async getMainColor(imgUrl) {
        var h = ''
        const result = await rgbaster(imgUrl); 
        console.log(444444444444)
        console.log(result[0])
        const rgb = result[0].color
        const parts = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
        if (parts) {
        h = rgbToHex(+parts[1], +parts[2], +parts[3]);
        } else {
        console.log("Invalid RGB string");
        }
        console.log('background:'+h)
        return 'background:'+h
    }
};
